<template>
  <div class="history-container">
    <!-- 加载中 -->
    <el-skeleton v-if="loading" :rows="4" animated />

    <!-- 订单列表 -->
    <div v-else class="order-list">
      <el-card
        v-for="order in orderList"
        :key="order.id"
        class="order-card"
        shadow="hover"
      >
        <div class="order-info">
          <p><strong>状态：</strong>{{ getOrderState(order.currentStatus) }}</p>
          <p><strong>类型：</strong>{{ order.orderType == 'NORMAL' ? '普通订单' : '超级订单' }}</p>
          <p><strong>创建时间：</strong>{{ order.createdAt }}</p>

          <!-- 图片缩略图 -->
          <div class="thumbnail-wrapper" @click="openPreviewDialog(order)">
            <img
              v-for="(imageId, idx) in order.imageIdList"
              :key="idx"
              :src="getThumbnailUrl(imageId)"
              alt="缩略图"
              class="thumbnail"
            />
          </div>

          <!-- 超级订单操作按钮 -->
          <div class="actions" v-if="order.orderType == 'PREMIUM' && order.currentStatus == 3">
            <el-button size="small" type="success" @click="handleSuperOrder(order.id, true)">
              满意并收货
            </el-button>
            <el-button size="small" type="warning" @click="handleSuperOrder(order.id, false)">
              不满意
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- PC端图片预览弹窗 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisiblePC"
      width="80%"
      v-if="!isMobile"
    >
      <!-- 添加下载按钮到顶部 -->
      <div class="dialog-header" style="margin-bottom: 15px;">
        <el-button type="primary" @click="downloadImages(selectedOrderId)">下载压缩包</el-button>
      </div>

      <div class="preview-images preview-grid-desktop">
        <img
          v-for="id in selectedImageIds"
          :key="id"
          :src="getImageUrl(id)"
          class="full-image"
        />
      </div>
    </el-dialog>

    <el-dialog
      title="图片预览"
      :visible.sync="previewVisibleMobile"
      fullscreen
      v-if="isMobile"
    >
      <div class="dialog-header">
        <el-button type="primary" @click="downloadImages(selectedOrderId)" block>下载压缩包</el-button>
      </div>

      <div class="preview-images preview-grid-mobile">
        <img
          v-for="id in selectedImageIds"
          :key="id"
          :src="getImageUrl(id)"
          class="full-image-mobile"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: "HistoryView",
  data() {
    return {
      loading: true,
      orderState: [],
      orderList: [],
      previewVisiblePC: false,
      previewVisibleMobile: false,
      selectedImageIds: [],
      selectedOrderId: null,
    };
  },
  computed: {
    isMobile() {
      return window.innerWidth < 768;
    },
  },
  mounted() {
    this.fetchOrders();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      if (window.innerWidth >= 768) {
        this.previewVisibleMobile = false;
      } else {
        if (this.previewVisiblePC) this.previewVisibleMobile = true;
      }
    },
    // 获取订单列表
    async fetchOrders() {
      try {
        const res = await this.$axios.get("/user/order/getOrderList");
        if (res.data.code == 1) {
          this.orderState = res.data.data.orderState;
          this.orderList = res.data.data.orderList.map(order => ({
            ...order,
            imageIdList: order.imageIdList || []
          }));
        } else {
          this.$message.error(res.data.msg);
        }
      } catch (e) {
        this.$message.error("获取订单失败");
        console.error(e);
      } finally {
        this.loading = false;
      }
    },

    // 获取状态文本
    getOrderState(index) {
      return this.orderState[index] || '未知状态';
    },

    // 获取图片地址（使用新接口）
    getImageUrl(imageId) {
      return `/api/user/minio/getImage/${imageId}`;
    },

    // 获取缩略图地址（假设可以通过参数控制尺寸）
    getThumbnailUrl(imageId) {
      return `${this.getImageUrl(imageId)}?size=small`;
    },

    // 打开预览弹窗
    openPreviewDialog(order) {
      this.selectedImageIds = order.imageIdList;
      this.selectedOrderId = order.id;
      if (this.isMobile) {
        this.previewVisibleMobile = true;
      } else {
        this.previewVisiblePC = true;
      }
    },

    // 下载当前订单的所有图片（压缩包）
    downloadImages(orderId) {
      window.open(`/api/user/minio/downloadImage/${orderId}`);
    },

    // 处理超级订单满意与否
    async handleSuperOrder(orderId, state) {
      try {
        const res = await this.$axios.put(`/user/order/updateSuperOrder/${orderId}/${state}`);
        if (res.data.code == 1) {
          this.$message.success("操作成功");
          this.fetchOrders(); // 刷新订单
        } else {
          this.$message.error(res.data.msg);
        }
      } catch (e) {
        this.$message.error("请求失败");
        console.error(e);
      }
    },
  },
  created() {
    this.$axios = axios.create({
      baseURL: '/api',
      withCredentials: true,
      timeout: 300000
    });
  }
};
</script>

<style scoped>
.history-container {
  padding: 30px 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #f9f9f9;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 加载动画居中 */
.el-skeleton {
  margin: 40px auto;
  max-width: 600px;
}

/* 订单卡片样式 */
.order-card {
  position: relative; /* 用于超级订单标签定位 */
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  background-color: #fff;
}

.order-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.order-info {
  padding: 16px;
}

.order-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #555;
}

.order-info strong {
  color: #333;
  font-weight: bold;
}

/* 超级订单徽章标签 */
.premium-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff9800;
  color: white;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  z-index: 1;
}

/* 图片缩略图区域 */
.thumbnail-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #ddd;
  transition: border-color 0.2s ease;
  cursor: pointer;
}

.thumbnail:hover {
  border-color: #409EFF;
}

/* 超级订单操作按钮 */
.actions {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.actions .el-button--small {
  flex: 1;
  font-weight: bold;
  border-radius: 6px;
  transition: all 0.2s ease;
  padding: 10px;
}

.actions .el-button--success {
  background-color: #4CAF50;
  color: white;
}

.actions .el-button--warning {
  background-color: #FFA726;
  color: white;
}

.actions .el-button--small:hover {
  opacity: 0.9;
}

/* 弹窗图片预览区域 */
.preview-grid-desktop,
.preview-grid-mobile {
  display: grid;
  gap: 20px;
}

.preview-grid-desktop {
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}

.full-image,
.full-image-mobile {
  width: 100%; /* 宽度占满单元格 */
  height: 250px; /* 设置固定的高度 */
  object-fit: cover; /* 确保图片按比例填充且不拉伸 */
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.full-image:hover,
.full-image-mobile:hover {
  transform: scale(1.02);
}

@media (max-width: 768px) {
  .full-image-mobile {
    max-width: 100%;
    height: 250px; /* 移动端也保持固定的图片高度 */
    margin-bottom: 10px;
  }

  .actions .el-button--small {
    width: 100%;
  }
}

.dialog-header {
  margin-bottom: 15px;
}
</style>